export class MatchMaker {
    players: number[];
    lastMatches: Map<number, number>;
    roundCount: number;

    constructor(playerCount: number) {
        this.players = Array.from({ length: playerCount }, (_, i) => i + 1);
        this.lastMatches = new Map();
        this.roundCount = 0;
    }

    rotateArray(arr: number[]): number[] {
        return [arr[arr.length - 1]].concat(arr.slice(0, -1));
    }

    generateRound(): [number, number][] {
        if (this.players.length < 2) {
            throw new Error("Not enough players for a match.");
        }

        // Rotate the array of players for new matches
        if (this.roundCount > 0) {
            this.players = this.rotateArray(this.players);
        }

        const matches: [number, number][] = [];
        for (let i = 0; i < this.players.length / 2; i++) {
            const player1 = this.players[i];
            const player2 = this.players[this.players.length - i - 1];

            // Avoid matching a player with themselves
            if (player1 === player2) continue;

            // Avoid repeating the last match
            if (this.lastMatches.get(player1) === player2 || this.lastMatches.get(player2) === player1) {
                continue;
            }

            matches.push([player1, player2]);
            this.lastMatches.set(player1, player2);
            this.lastMatches.set(player2, player1);
        }

        this.roundCount++;
        return matches;
    }

    removePlayer(playerId: number): void {
        this.players = this.players.filter(player => player !== playerId);
        this.lastMatches.delete(playerId);
    }

    start() {
        // 生成100回合的匹配
        for (let i = 0; i < 100; i++) {
            console.log(`Round ${i + 1}`, this.generateRound());

            // 模拟玩家淘汰（这里只是为了演示）
            if (i === 49) { // 假设在第50回合时淘汰一个玩家
                this.removePlayer(8);
            }
        }
    }
}



